Randomize JSON Array in jQuery


In this tutorial, I will explain how to randomise a JSON  Array by using jQuery to get some random character set from JSON Object Array. As usual, I will explain the function with a real life example. Our aim is to accept 3 numbers from the user between 1 to 9 and then output 3 random characters correspond to the individual number. Each number store 3 alphabets eg 1 store A, B, C similarly 2 store D, E, F and 3 store G, H, I etc. If user input is 132 then our required output is any single random letter from ABC and GHI and DEF (For example BID). A tricky problem right? but actually, you can easily solve a tricky problem like this in javascript by storing data in JSON format and by using jQuery a fast, small, and feature-rich JavaScript library. 

SO LET'S START CODING

The complete javascript code for achieving above task is given below.

<script>
	 $(function(){ // Shortform for $(document).ready(function(){});
		var data = {
			"1": ["A", "B", "C"],
			"2": ["D", "E", "F"],
			"3": ["G", "H", "I"],
			"4": ["J", "K", "L"],
			"5": ["M", "N", "O"],
			"6": ["P", "Q", "R"],
			"7": ["S", "T", "U"],
			"8": ["V", "W", "X"],
			"9": ["Y", "Z"]
		};
				
        $('#form').on('submit', function (e) {
            e.preventDefault();         
			var input = $("#numbers").val();
            var input_array = input.split('');
			var alphabet_array = [];
			var output_array = [];

			$.each(input_array, function( index, number ) {				

				$.each(data[number], function( index, alphabet ) {
					alphabet_array.push(alphabet);
				});
				
				output_array.push(alphabet_array[Math.floor(Math.random()*alphabet_array.length)]);
				
				alphabet_array =  [];
			});
			$("#output").html(output_array);
        });
    });	
	</script>

Now let me explain the program one by one.

First, we need to store the data as a JSON array. JSON (JavaScript Object Notation) is a lightweight data-interchange format. Arrays in JSON are almost the same as arrays in JavaScript.In JSON, array values must be of type string, number, object, array, boolean or null.

Second, we need to store submit the value of input numbers into individual array elements. In Javascript, the split() method is used to split a string into an array of substrings and returns the new array.If an empty string ("") is used as the separator, the string is split between each character.

Syntax
string.split(separator, limit)

 

Now we use a foreach loop to iterate over our numbers and we use another foreach loop to iterate over individual alphabets corresponds to that numbers. We store alphabets of the individual number in an alphabet_array. In jQuery, .each() method is an alternative to javascript forEach() method. I used it more often in my programming than forEach() method but it is definitely up to your choice.

Now we need to pick a random alphabet from this alphabet array. We use Math.random() method of javascript for this. The Math.random() returns a random number between 0 (inclusive),  and 1 (exclusive). Math.random() used with Math.floor() can be used to return random integers.

Math.floor(Math.random() * 10);     // returns a number between 0 and 9

 

Now using the random key value we will extract the alphabet corresponds to alphabet_array and store it on an output_array. The alphabet_array is unset at end of each foreach loop to avoid duplication. 

Now let's make our program a little colourful by giving some HTML and CSS to it. I used Bootstrap for achieving it. So the complete code for the index.html page is given below.

<html>
  <head>
    <title>Randomize JSON Array Demo</title>
	
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	
  </head>
  <body>
    <div class="container">
		<div class="row">
			<div class="col-md-6 col-md-offset-3">
				<h2 class="text-center" style="color:#337ab7;"><u>Randomize JSON Array Demo</u></h2>
				<form  id="form" method="POST" >
					<div class="form-group">
						<label for="inputName" class="control-label">Numbers</label>
						<input type="text" id="numbers" pattern="[1-9]{1,3}"  class="form-control"  placeholder="Enter Any 3 Numbers From 1 to 9" required/>
					</div>
					<button class="btn btn-block btn-primary"  type="submit" name="submit">Submit</button>
				</form>
				<h2 class="text-center" style="color:#337ab7;" id="output">
				</h2>
				<table class="table table-bordered table-striped text-center">
					<thead>
						<tr>
							<th  class="text-center">Number</th>
							<th  class="text-center">Values</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td>1</td>
							<td>A B C</td>
						</tr>
						<tr>
							<td>2</td>
							<td>D E F</td>
						</tr>
						<tr>
							<td>3</td>
							<td>G H I</td>
						</tr>
						<tr>
							<td>4</td>
							<td>J K L</td>
						</tr>
						<tr>
							<td>5</td>
							<td>M N O</td>
						</tr>
						<tr>
							<td>6</td>
							<td>P Q R</td>
						</tr>
						<tr>
							<td>7</td>
							<td>S T Q</td>
						</tr>
						<tr>
							<td>8</td>
							<td>V W X</td>
						</tr>
						<tr>
							<td>9</td>
							<td>Y Z</td>
						</tr>
					</tbody>
				  </table>
				
			</div>
		</div>
		
	<br>
	</div>
	<script>
	 $(function(){ // Shortform for $(document).ready(function(){});
		var data = {
			"1": ["A", "B", "C"],
			"2": ["D", "E", "F"],
			"3": ["G", "H", "I"],
			"4": ["J", "K", "L"],
			"5": ["M", "N", "O"],
			"6": ["P", "Q", "R"],
			"7": ["S", "T", "U"],
			"8": ["V", "W", "X"],
			"9": ["Y", "Z"]
		};
				
        $('#form').on('submit', function (e) {
            e.preventDefault();         
			var input = $("#numbers").val();
            var input_array = input.split('');
			var alphabet_array = [];
			var output_array = [];

			$.each(input_array, function( index, number ) {				
				
				$.each(data[number], function( index, alphabet ) {
					alphabet_array.push(alphabet);
				});
				
				output_array.push(alphabet_array[Math.floor(Math.random()*alphabet_array.length)]);
				
				alphabet_array =  [];
			});
			$("#output").html(output_array);
        });
    });	
	</script>
	
  </body>
</html>

 

Note I used HTML validation only in this case which is only necessary in the case of demo programs like this. The HTML input validation offers regular expression checking for advanced pattern matching. The pattern attribute is used for achieving it but remember that it will work only in text inputs. 

The output image of above program is given below.

Randomize JSON Array Demo - shareurcodes.com

 The Demo

You can demo above program by visiting following link.

https://shareurcodes.com/demo/random.html

If anybody has any suggestions or doubts or need any help comment below and I try will response to every one of you as early as possible.


Similar Posts

Web development
16th May 2017 04:44:53 AM
Javascript jQuery Bootstrap HTML & CSS
8572

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.